import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { encryptPassword } from 'src/utils/cryptogram';
import { UserService } from '../user/user.service';


@Injectable()
export class AuthService {
    constructor(private readonly userService:UserService,private readonly jwtService:JwtService){}
    // JWT验证-校验用户信息
    async validateUser(phone: string,pwd: string): Promise<any>{
        console.log('JWT验证 - Step 2: 校验用户信息');
        const user =await this.userService.findOne(phone);
        if(user){
            const hashedPwd = user.pwd;
            const salt = user.pwd_salt;
            // 通过密码盐，加密传参，再与数据库里的比较，判断是否相等
            const hashPwd = encryptPassword(pwd,salt)
            if(hashedPwd===hashPwd){
                // 密码正确
                return {
                    code:1, 
                    user
                }
            }else{
                // 密码错误
                return {
                    code:0,
                    msg:'密码错误'
                }
            }
        }else{
            return {
                code:0,
                msg:'用户不存在'
            }
        }
    }

    // JWT验证-处理jwt签证
    async certificate(user:any){
        const payload = {name:user.name,id:user.id,phone:user.phone}
        console.log('JWT验证 - Step 3: 处理 jwt 签证');
        try {
            const token = this.jwtService.sign(payload)
            return{
                code:1,
                msg:'登录成功',
                data:{
                    token
                }
            }
        } catch (error) {
            return {
                code:503,
                msg:`系统错误：${error}`
            }
        }
    }
}
